package com.lengxf.i18n.listener;

import cn.hutool.core.map.MapUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.read.metadata.holder.ReadSheetHolder;
import com.alibaba.excel.read.metadata.property.ExcelReadHeadProperty;
import com.lengxf.i18n.config.PlaceholderResolver;
import lombok.Getter;
import lombok.Setter;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;

import java.lang.reflect.Field;
import java.util.*;


@Setter
@Getter
public class I18nAnalysisEventListener<T> extends AnalysisEventListener<T> {

    private final MessageSource messageSource = SpringUtil.getBean(MessageSource.class);

    private List<T> list = new ArrayList<>();

    @Override
    public void invoke(T object, AnalysisContext context) {
        list.add(object);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        ReadSheetHolder readSheetHolder = context.readSheetHolder();
        ExcelReadHeadProperty originExcelHeadPropertyData = new ExcelReadHeadProperty(context.currentReadHolder(),
                readSheetHolder.getClazz(), null);
        Map<Integer, Head> originHeadMapData = originExcelHeadPropertyData.getHeadMap();
        Map<Integer, Head> newHeadMapData = new HashMap<>(originHeadMapData.size());
        Map<String, Integer> inverseHeadMap = MapUtil.inverse(headMap);
        for (Integer key : originHeadMapData.keySet()) {
            Head head = originHeadMapData.get(key);
            Field field = head.getField();
            if (!field.isAnnotationPresent(ExcelProperty.class)) {
                continue;
            }
            ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);
            String i18nHead = (excelProperty.value())[0];
            String actHead = PlaceholderResolver.getDefaultResolver()
                    .resolveByRule(i18nHead, this::getMessage);
            Integer index = inverseHeadMap.get(actHead);
            if (index != null) {
                head.setHeadNameList(List.of(actHead));
                newHeadMapData.put(index, head);
            }
        }
        readSheetHolder.excelReadHeadProperty().setHeadMap(newHeadMapData);
    }

    private String getMessage(String code) {
        Locale locale = LocaleContextHolder.getLocale();
        return messageSource.getMessage(code, null, locale);
    }

}
